package fr.utbm.gi.in56.ads;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.utbm.gi.in56.database.DatabaseServlet;
import fr.utbm.gi.in56.error.ErrorType;
import fr.utbm.gi.in56.notification.NotificationType;
import fr.utbm.gi.in56.user.UserBean;
import fr.utbm.gi.in56.user.UserManager;

/**
 * Servlet implementation class AdStateServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet("/AdStateServlet")
public class AdStateServlet extends MyAdsServlet
{
	private static final long	serialVersionUID	= 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AdStateServlet()
	{
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		request.setCharacterEncoding( "UTF-8" ); //$NON-NLS-1$
		
		// Get the ad id
		String adIdString = request.getParameter( "adId" ); //$NON-NLS-1$
		int adId = 0;
		try
		{
			adId = Integer.parseInt( adIdString );
		}
		catch ( NumberFormatException e )
		{
			forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_ID );
			return;
		}
		
		// Get the ad type
		String adType = request.getParameter( "adType" ); //$NON-NLS-1$
		AdType adTypeEnum = AdType.NONE;
		try
		{
			adTypeEnum = AdType.valueOf( adType.toUpperCase() ); 
		}
		catch ( Exception _exception ) // IllegalArgumentException or NullPointerException
		{
			forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_TYPE );
			return;
		}
		
		AdsManager adsMg = new AdsManager( getConnection() );

		String requestedAction = request.getParameter( "action" ); //$NON-NLS-1$
		if ( requestedAction == null )
		{
			forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_ACTION );
			return;
		}
		else if ( requestedAction.compareTo( "delete" ) == 0 ) //$NON-NLS-1$
		{
			ErrorType result = adsMg.deleteAd( adId, adTypeEnum );
			if ( result != ErrorType.NONE )
			{
				forwardToErrorPage( request, response, result );
				return;
			}
		}		
		
		forwardAds( request, response );
		
		RequestDispatcher rd = request.getRequestDispatcher( "MyAdsServlet" ); //$NON-NLS-1$
		rd.forward( request, response );
	}
	
	@Override
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		request.setCharacterEncoding( "UTF-8" ); //$NON-NLS-1$
		
		// Get the ad id
		String adIdString = request.getParameter( "adId" ); //$NON-NLS-1$
		int adId = 0;
		try
		{
			adId = Integer.parseInt( adIdString );
		}
		catch ( NumberFormatException e )
		{
			forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_ID );
			return;
		}
		
		// Get the ad type
		String adType = request.getParameter( "adType" ); //$NON-NLS-1$
		AdType adTypeEnum = AdType.NONE;
		try
		{
			adTypeEnum = AdType.valueOf( adType.toUpperCase() ); 
		}
		catch ( Exception _exception ) // IllegalArgumentException or NullPointerException
		{
			forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_TYPE );
			return;
		}
		
		AdsManager adsMg = new AdsManager( getConnection() );
		
		String requestedAction = request.getParameter( "action" ); //$NON-NLS-1$
		if ( requestedAction == null )
		{
			forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_ACTION );
			return;
		}
		else if ( requestedAction.compareTo( "close" ) == 0 ) //$NON-NLS-1$
		{
			String secondUserLogin = request.getParameter( "user" ); //$NON-NLS-1$
			if ( secondUserLogin == null || secondUserLogin.isEmpty() )
			{
				forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_USER );
				return;
			}
			
			ErrorType result = adsMg.changeAdState( adId, adTypeEnum,
					AdState.WAITING_FOR_RATING, secondUserLogin );
			if ( result != ErrorType.NONE )
			{
				forwardToErrorPage( request, response, result );
				return;
			}
		}
		else if ( requestedAction.compareTo( "confirm" ) == 0 ) //$NON-NLS-1$
		{
			String secondUserLogin = request.getParameter( "user" ); //$NON-NLS-1$
			if ( secondUserLogin == null || secondUserLogin.isEmpty() )
			{
				forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_USER );
				return;
			}
			
			ErrorType result = adsMg.changeAdState( adId, adTypeEnum,
					AdState.WAITING_FOR_RATING, secondUserLogin );
			if ( result != ErrorType.NONE )
			{
				forwardToErrorPage( request, response, result );
				return;
			}
		}
		else if ( requestedAction.compareTo( "rate" ) == 0 ) //$NON-NLS-1$
		{
			int rating = Integer.parseInt( request.getParameter( "rating" ) );

			String secondUserLogin = request.getParameter( "user" ); //$NON-NLS-1$
			if ( secondUserLogin == null || secondUserLogin.isEmpty() )
			{
				forwardToErrorPage( request, response, ErrorType.ADS_STATE_INVALID_USER );
				return;
			}
			
			// Get the current user
			HttpSession session = request.getSession( true );
			UserBean user = (UserBean)session.getAttribute( "currentSessionUser" ); //$NON-NLS-1$
			
			UserManager userMg = new UserManager( getConnection() );
			ErrorType result = userMg.addRating( secondUserLogin, user.getLogin(), adId, adTypeEnum, rating );
			if ( result != ErrorType.NONE )
			{
				forwardToErrorPage( request, response, result );
				return;
			}
		}
		
		RequestDispatcher rd = request.getRequestDispatcher( "MyAdsServlet" ); //$NON-NLS-1$
		rd.forward( request, response );
	}

	/**
	 * Sets the error as request attribute and forward to error page.
	 * 
	 * @param _error the error
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void forwardToErrorPage( HttpServletRequest request,
			HttpServletResponse response, ErrorType _error ) throws ServletException, IOException
	{
		request.setAttribute( "error", _error ); //$NON-NLS-1$
		RequestDispatcher rd = request.getRequestDispatcher("error.jsp"); //$NON-NLS-1$
		rd.forward( request, response );
	}
}
